const clientGroupId = localStorage.getItem("clientGroupId");

let WebApp = window.Telegram.WebApp;
WebApp.expand();
WebApp.BackButton.hide();
WebApp.isClosingConfirmationEnabled = true;

const logOutButton = document.getElementById("logOut");
const scheduleMoreButton = document.getElementById("scheduleMoreButton");
let AllSсheduleItem = "";
const goToPayPage = document.getElementById("payLoad");
const innerLesson = document.querySelector(".scheduleBody");
const todaySchedule = document.getElementById("todaySchedule");

goToPayPage.addEventListener("click", () => {
  window.location.href = "/pay";
});

const request = [{ name: "next_lesson" }];

if (clientGroupId != "n/a" && clientGroupId != undefined) {
  fetch("/nextlessons", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ clientGroupId: clientGroupId }),
  })
    .then((res) => res.json())
    .then((data) => {
      displayLesson(data);
    })
    .catch((err) => {
      console.log(err);
    });
}

let todayDate = new Date();

const displayLesson = (lesson) => {
  if (lesson.length > 0) {
    let flag = true;
    lesson.forEach(
      ({ lesson_name, lesson_date, teacher, lesson_date_for_js }, index) => {
        const match = lesson_date_for_js.match(/-?\d+(\.\d+)?/g);
        let lessonDay = parseInt(match[2]);
        let lessonMount = parseInt(match[1]);

        if (
          lessonDay == todayDate.getDate() &&
          lessonMount == todayDate.getMonth()
        ) {
          innerLesson.innerHTML += `
    <div class="scheduleItem">
      <div class="scheduleAbout">
        <h2 class="scheduleDate">
         ${lesson_date}
        </h2>
        <p class="sixe">${teacher}</p>
        <p class="sixe">${lesson_name}</p>
      </div>
    </div>`;
          flag = false;
        }
        if (lessonDay != todayDate.getDate() && flag) {
          todaySchedule.innerText = "На сегодня нет занятий";
          innerLesson.innerHTML = `
          <div class="scheduleItem">
            <div class="scheduleAbout">
              <h2 class="scheduleDate">
               Перейдите в расписание
              </h2>
            </div>
          </div>`;
        }
      }
    );
  } else {
    innerLesson.innerHTML += `
    <div class="scheduleItem">
      <div class="scheduleAbout">
        <h2 class="scheduleDate">
         Нет занятий в расписании
        </h2>
      </div>
    </div>`;
  }
  AllSсheduleItem = document.querySelectorAll(".scheduleItem");

  for (let i = 0; i < AllSсheduleItem.length; i++) {
    AllSсheduleItem[i].addEventListener("click", goToSchedule);
  }
};

fetch("/materials")
  .then((res) => res.json())
  .then((data) => {
    displayPopUp(data);
    displayMaterial(data);
  });

const popUp = document.getElementById("referrer");
const nameMaterialPopUp = document.getElementById("nameMaterialPopUp");
const descriptionPopUp = document.getElementById("descriptionPopUp");
const zero = document.getElementById("zero");

const innerPopUp = document.querySelector(".material");
const downLoad = document.getElementById("downLoad");

const displayMaterial = (data) => {
  const test = document.querySelectorAll(".openPopUp");

  for (let i = 0; i < test.length; i++) {
    test[i].addEventListener("click", () => {
      downLoad.setAttribute("href", data[i].url);

      popUp.style.display = "flex";
      nameMaterialPopUp.innerText = data[i].name;
      descriptionPopUp.innerText = data[i].about;
      zero.style.backgroundImage = `url(${data[i].src})`;
    });
  }
};

const displayPopUp = (data) => {
  data.forEach(({ name, src }, index) => {
    innerPopUp.innerHTML += `
        <div class="openPopUp" value="0">
            <img class="imgContainer" src="${src}"/>
            <h3 class="labelFromImg">${name}</h3>
        </div>`;
  });
};

popUp.addEventListener("click", (e) => {
  if (e.target.id === "referrer") {
    popUp.style.display = "none";
  }
});

const closePopUpButton = document.getElementById("closeBtn1");

closePopUpButton.addEventListener("click", () => {
  popUp.style.display = "none";
});

const goToSchedule = () => {
  window.location.href = "/schedule/";
};

scheduleMoreButton.addEventListener("click", goToSchedule);

const innerSlideBar = document.querySelector(".owerFlowWindod");

fetch("/banners")
  .then((res) => res.json())
  .then((data) => {
    displayBanners(data);
  });

const displayBanners = (data) => {
  data.forEach(({ name, src, about }, index) => {
    innerSlideBar.innerHTML += `
    <div class="slide" style="background-image: url('${src}');">
    <h2 class="h3Ower">${name}</h2>
    <p class="tooltip">${about}</p>
  </div>`;
  });
};

// --------- кнопка регистрации

// const regButton = document.getElementById("regis");

// regButton.addEventListener("click", () => {
//   window.location.href = "/registration/";
// });

/// -------------


// WebApp.MainButton.show();
